﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ToolS
{
    public class XmlHelper
    {

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">可序列化的实体</param>
        /// <returns>序列化后的字符串</returns>
        public static string ObjectSerialize(object obj)
        {
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                    xmlSerializer.Serialize(stream, obj);
                    byte[] buf = stream.ToArray();
                    string xml = Encoding.UTF8.GetString(buf);
                    stream.Close();

                    return xml;
                }
            }
            catch
            {
                return string.Empty;
            }
        }

        public static T Deserialize<T>(string xml)
        {
            if (string.IsNullOrWhiteSpace(xml))
            {
                return default(T);
            }

            using (TextReader reader = new StringReader(xml))
            {
                XmlReaderSettings settings = new XmlReaderSettings
                {
                    ConformanceLevel = ConformanceLevel.Fragment,
                    DtdProcessing = DtdProcessing.Ignore,
                    IgnoreProcessingInstructions = true,
                    IgnoreWhitespace = true,
                    IgnoreComments = true,
                    CheckCharacters = false // 跳过非法字符的检查，解决公司方法的报错问题
                };

                using (XmlReader xreader = XmlTextReader.Create(reader, settings))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return (T)serializer.Deserialize(xreader);
                }
            }
        }
    }
}
